import axios from "axios";
import config from "@/config/index";

import { ElMessage } from "element-plus";
import "element-plus/theme-chalk/el-message.css";

let http = axios.create({
  // baseURL: config.baseApi,
  timeout: 5000
});

//请求拦截
http.interceptors.request.use(
  (config) => {
    console.log(config, "config");
    return config;
  },
  (e) => {
    return Promise.reject(e);
  }
);

http.interceptors.response.use(
  (res) => {
    // console.log(res,'response--')
    if (res.data.code == 500) {
      ElMessage.warning(res.data.msg || "网络请求异常，请重新请求");
    } else {
      return res;
    }
  },
  (e) => {
    return Promise.reject(e);
  }
);

//封装一个核心函数
function request(options) {
  options.method = options.method || "get";

  if (options.method.toLowerCase() == "get") {
    options.params = options.params || options.data;
  }

  let isMock = config.isMock;
  if (typeof options.isMock !== "undefined") {
    isMock = options.isMock;
  }
  //开发模式
  if (config.env == "prod") {
    // http.defaults.baseURL = config.baseApi;
  } else {
    // http.defaults.baseURL = isMock ? config.mockApi : config.baseApi;
    http.defaults.baseURL = isMock ? config.mockApi : "";
  }
  return http(options);
}

export default request;
